//
//  HTNetworkManager.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/9.
//

import Foundation
import Moya
import HandyJSON

/// 超时时长
private var var_requestTimeOut: Double = 30

//这个closure存放了一些moya进行网络请求前的一些数据,可以在闭包中设置公共headers
private let var_endpointClosure = { (target: HTEnumNetworkService) -> Endpoint in
  var var_endpoint: Endpoint = MoyaProvider.defaultEndpointMapping(for: target)
  return var_endpoint
}
//这个闭包是moya提供给我们对网络请求开始前最后一次机会对请求进行修改，比如设置超时时间（默认是60s），禁用cookie等
private let var_requestClosure = { (endpoint: Endpoint, done: @escaping MoyaProvider<HTEnumNetworkService>.RequestResultClosure) -> Void in

  do {
    var var_request = try endpoint.urlRequest()
    // 设置请求时长
    var_request.timeoutInterval = var_requestTimeOut
    // 打印请求参数
    if let var_requestData = var_request.httpBody {
      print("请求的url：\(var_request.url!)" + "\n" + "\(var_request.httpMethod ?? "")" + "发送参数" + "\(String(data: var_request.httpBody!, encoding: String.Encoding.utf8) ?? "")")
    } else {
      print("请求的url：\(var_request.url!)" + "\(String(describing: var_request.httpMethod))")
    }
//
//    if let header = var_request.allHTTPHeaderFields {
//      print("请求头内容\(header)")
//    }

    done(.success(var_request))
  } catch {
    done(.failure(MoyaError.underlying(error, nil)))
  }

}

private let var_networkProvider = MoyaProvider<HTEnumNetworkService>(endpointClosure: var_endpointClosure, requestClosure: var_requestClosure, plugins: [HTNetworkPlugin()], trackInflights: false)


struct HTNetworkManager {
  var var_provider = var_networkProvider

  func ht_request(_ target: HTEnumNetworkService, completion: @escaping (HTResponse) -> Void = {_ in }) {
    var_networkProvider.request(target) { result in
      do{
        switch result {
        case let .success(response):
          var info = HTResponse.deserialize(from: String(data: response.data, encoding: String.Encoding.utf8)!)
          if info == nil {
            info = HTResponse()
          }
          completion(info!)
        case let .failure(error):
          var errorM = HTResponse()
          errorM.var_message = error.localizedDescription
          completion(errorM)
        }
      } catch _ {
        print("请求失败")
      }
    }
  }

  func ht_request<T: HandyJSON>(_ target: HTEnumNetworkService, completion: @escaping (HTResponse, T?) -> Void = {_,_ in }) {
    var_networkProvider.request(target) { result in
      do{
        switch result {
        case let .success(response):
          var info = HTResponse.deserialize(from: String(data: response.data, encoding: String.Encoding.utf8)!)
          let obj = T.deserialize(from: info?.var_data as? Dictionary)
          if info == nil {
            info = HTResponse()
          }
          completion(info!, obj)
        case let .failure(error):
          var errorM = HTResponse()
          errorM.var_message = error.localizedDescription
          completion(errorM,nil)
        }
      } catch _ {
        print("请求失败")
      }
    }
  }

  // 埋点请求
  func ht_requestForBuried(_ target: HTEnumNetworkService) {
    var_networkProvider.request(target) { result in

    }
  }
}
